package com.ljkj.cordial.chat.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lanjiu.lib.business.FileTransmissionManager;
import com.lanjiu.lib.business.OriginalPictureVideoTransmissionCreator;
import com.lanjiu.lib.business.listener.FileTransmissionListener;
import com.lanjiu.lib.imclient.bus.EventConstants;
import com.lanjiu.lib.imclient.bus.MessageEvent;
import com.lanjiu.lib.imclient.dto.FriendDto;
import com.lanjiu.lib.imclient.dto.GroupDto;
import com.lanjiu.lib.imclient.dto.SettingsDto;
import com.lanjiu.lib.imclient.dto.VersionDto;
import com.lanjiu.lib.imclient.dto.extra.UserChatTable;
import com.lanjiu.lib.imclient.dto.notify.SysNotifyDto;
import com.lanjiu.lib.imclient.dto.user.UserDto;
import com.lanjiu.lib.imclient.ims.IMSClientHelper;
import com.lanjiu.lib.imclient.ims.IMSContacts;
import com.lanjiu.lib.imclient.ims.IMSUtils;
import com.lanjiu.lib.imclient.user.UserPreferences;
import com.lanjiu.lib.utils.CollectionUtils;
import com.lanjiu.lib.utils.NetUtils;
import com.lanjiu.lib.utils.log.Logger;
import com.ljkj.cordial.chat.BuildConfig;
import com.ljkj.cordial.chat.R;
import com.ljkj.cordial.chat.adapter.MainFragmentPagerAdapter;
import com.ljkj.cordial.chat.base.ChatApp;
import com.ljkj.cordial.chat.bean.Canstants;
import com.ljkj.cordial.chat.bean.GroupSimpleBean;
import com.ljkj.cordial.chat.dao.BusinessLeaveTableDao;
import com.ljkj.cordial.chat.dao.DbController;
import com.ljkj.cordial.chat.dao.notify.ChatContentTable;
import com.ljkj.cordial.chat.dao.notify.FriendTable;
import com.ljkj.cordial.chat.dao.notify.GroupMemberTable;
import com.ljkj.cordial.chat.dao.notify.GroupTable;
import com.ljkj.cordial.chat.dialog.UpdateDialog;
import com.ljkj.cordial.chat.fragment.NavChatFragment;
import com.ljkj.cordial.chat.fragment.NavContactFragment;
import com.ljkj.cordial.chat.fragment.NavGroupFragment;
import com.ljkj.cordial.chat.fragment.NavMeFragment;
import com.ljkj.cordial.chat.fragment.NavNotifyFragment;
import com.ljkj.cordial.chat.notify.AppBadgerManager;
import com.ljkj.cordial.chat.presenter.ChatMainPresenter;
import com.ljkj.cordial.chat.ui.AppEventActivity;
import com.ljkj.cordial.chat.ui.views.ChatMainView;
import com.ljkj.cordial.chat.util.InitializeKit;
import com.ljkj.cordial.chat.util.ObserverThread;
import com.ljkj.cordial.chat.util.SharedUserUtils;
import com.ljkj.cordial.chat.widget.MainMenuPop;
import com.ljkj.cordial.lengthtcpheartbeat.NetStateChangeObserver;
import com.ljkj.cordial.lengthtcpheartbeat.NetStateChangeReceiver;
import com.ljkj.cordial.lengthtcpheartbeat.NetworkType;
import com.ljkj.cordial.lengthtcpheartbeat.OnClientConnectedListener;
import com.ljkj.cordial.lengthtcpheartbeat.ScreenStateChangeObserver;
import com.ljkj.cordial.lengthtcpheartbeat.ScreenStateChangeReceive;
import com.ljkj.cordial.lengthtcpheartbeat.TcpLengthHeartbeatBroadcastReceive;
import com.nic.view.util.JToast;
import com.nic.view.util.glide.GlideUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 亲信主页面
 */
public class ChatMainActivity extends AppEventActivity<ChatMainView> implements NetStateChangeObserver, ChatMainView.ChatMainCallback, ScreenStateChangeObserver, OnClientConnectedListener {


    @BindView(R.id.nav_view)
    BottomNavigationView navView;
    @BindView(R.id.frame_content)
    FrameLayout frameContent;
    @BindView(R.id.iv_no_wifi)
    ImageView ivNoWifi;
    @BindView(R.id.tv_no_wifi)
    TextView tvNoWifi;
    @BindView(R.id.tv_chat_num)
    TextView tvChatNum;
    @BindView(R.id.tv_notify_num)
    TextView tvNotifyNum;
    @BindView(R.id.viewPager)
    ViewPager pagerView;

    //    private Fragment currtShowFragment;
    private NavChatFragment navChatFragment;
    private NavContactFragment navContactFragment;
    private NavGroupFragment navGroupFragment;
    private NavMeFragment navMeFragment;
    private NavNotifyFragment navNotifyFragment;
    private MainMenuPop mainMenuPop;
    private ChatMainPresenter presenter;

    private int mRequestOfflineMessageDelayMillis;
    private boolean isInitializeData;
    private MainFragmentPagerAdapter adapter;
    private boolean manualDraging;
    private ConnectHandler connectHandler;

    /**
     * 亲信消息数量
     */
    private long chatSum;
    /**
     * 通知消息数量
     */
    private long notifySum;


    public void setChatSum(long chatSum) {
        this.chatSum = chatSum;
        showChatSumTitle();

    }

    public void setNotifySum(long notifySum) {
        this.notifySum = notifySum;
        showNotifySumTitle();

    }

    public void showChatSumTitle() {
        //            setToolbarTitle(String.format("亲信(%d)", chatSum));
        if (chatSum == 0) {
            tvChatNum.setVisibility(View.GONE);
        } else {
            tvChatNum.setVisibility(View.VISIBLE);
            tvChatNum.setText("" + chatSum);
        }
    }

    public void showNotifySumTitle() {
        //            setToolbarTitle(String.format("通知(%d)", notifySum));
        if (notifySum == 0) {
            tvNotifyNum.setVisibility(View.GONE);
        } else {
            tvNotifyNum.setVisibility(View.VISIBLE);
            tvNotifyNum.setText("" + notifySum);
        }
    }


    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {

            switch (item.getItemId()) {
                case R.id.navigation_chat:
//                    setTheme(ChatMainActivity.this, true, R.color.title_color, R.color.title_color);
//                    if (navChatFragment == null) {
//                        navChatFragment = new NavChatFragment();
//                    }
//                    selectShow(navChatFragment);
                    setTopTab(0);
                    return true;
                case R.id.navigation_contact:
//                    setTheme(ChatMainActivity.this, true, R.color.title_color, R.color.title_color);
//                    if (navContactFragment == null) {
//                        navContactFragment = new NavContactFragment();
//                    }
//                    selectShow(navContactFragment);
                    setTopTab(1);
                    return true;
                case R.id.navigation_group:
//                    setTheme(ChatMainActivity.this, true, R.color.title_color, R.color.title_color);
//                    if (navGroupFragment == null) {
//                        navGroupFragment = new NavGroupFragment();
//                    }
//                    selectShow(navGroupFragment);
                    setTopTab(2);
                    return true;
                case R.id.navigation_notify:
//                    setTheme(ChatMainActivity.this, true, R.color.title_color, R.color.title_color);
//                    if (navNotifyFragment == null) {
//                        navNotifyFragment = new NavNotifyFragment();
//                    }
//                    selectShow(navNotifyFragment);
                    setTopTab(3);
                    return true;
                case R.id.navigation_me:
//                    setTheme(ChatMainActivity.this, true, R.color.white, R.color.white);
//                    if (navMeFragment == null) {
//                        navMeFragment = NavMeFragment.newInstance(() -> obtainView().doLogout());
//                    }
//                    selectShow(navMeFragment);
                    setTopTab(4);
                    return true;
            }
            return false;
        }
    };

    @Override
    protected int setupEventBusRegSite() {
        return EVENT_REG_ON_CREATE;
    }

    @Override
    public int getContentLayoutId() {
        return R.layout.activity_chat_main;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        getToolbar().setNavigationIcon(null);
        ChatApp.getInstance().setExitFlag(false);
        isInitializeData = getIntent().getBooleanExtra("is_initialize_data", true);
        mainMenuPop = new MainMenuPop(this);
        mainMenuPop.setOnAddFriendListener(new MainMenuPop.OnAddFriendListener() {
            @Override
            public void onClick(View v) {
                SearchFriendActivity.jumpTo(mContext, Canstants.SEARCH_TYPE_FRIEND_GROUP);
            }
        });
        mainMenuPop.setOnCreateGroupListener(new MainMenuPop.OnCreateGroupListener() {
            @Override
            public void onClick(View v) {
                InviteFriendActivity.jumpToCreate((Activity) mContext);
            }
        });
        getToolbarRightIv().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                switch (navView.getSelectedItemId()) {
//                    case R.id.navigation_chat:
                mainMenuPop.getPopupWindow().showAsDropDown(view, false);
//                        break;
//                    case R.id.navigation_contact:
//                        openActivity(SearchFriendActivity.class);
//                        break;
//                    case R.id.navigation_group:
//                        openActivity(SearchFriendActivity.class);
//                        break;
//                }
            }
        });
        getToolbarRightIv2().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                SearchFriendActivity.jumpTo(mContext, Canstants.SEARCH_TYPE_FRIEND_GROUP);
                startActivity(new Intent(ChatMainActivity.this, SearchLocalActivity.class));
            }
        });
        navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        navChatFragment = NavChatFragment.newInstance(this::selectNum);
        selectShow(navChatFragment);
//        updateAvatar();
        isFromNotify();
        navContactFragment = new NavContactFragment();
        navGroupFragment = new NavGroupFragment();
        navNotifyFragment = NavNotifyFragment.newInstance(this::selectNum);
        navMeFragment = NavMeFragment.newInstance(() -> obtainView().doLogout());

        List<Fragment> fragments = new ArrayList<>();
        fragments.add(navChatFragment);
        fragments.add(navContactFragment);
        fragments.add(navGroupFragment);
        fragments.add(navNotifyFragment);
        fragments.add(navMeFragment);
        adapter = new MainFragmentPagerAdapter(getSupportFragmentManager(), fragments);
        pagerView.setOffscreenPageLimit(5);
        pagerView.setAdapter(adapter);
        pagerView.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                if (manualDraging) {
                    switchNav(i);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_IDLE://自动切换
                        manualDraging = false;
                        break;
                    case ViewPager.SCROLL_STATE_DRAGGING://手动切换
                        manualDraging = true;
                        break;
                    case ViewPager.SCROLL_STATE_SETTLING:
                        break;
                    default:
                        break;
                }
            }
        });
        setTopTab(0);

    }
//
//    public void updateAvatar() {
//        UserTableBean userInfo = UserTableBean.getCurrentUser();
//        if (!TextUtils.isEmpty(userInfo.getAvatar())) {
//            AlbumManageUtil.getInstance().downLoadFileFriendAvatar(userInfo.getAvatar(), userInfo.getUserId(), new AlbumManageUtil.OnFileResponse() {
//                @Override
//                public void onResult(String url, String fileId) {
//                    if (!TextUtils.isEmpty(fileId)) {
//                        userInfo.setAvatarPath(fileId);
//                        UserTableBean.update(userInfo);
//                    }
//
//                }
//            });
//        }
//    }

    public void isFromNotify() {
        Intent notify = getIntent();
        if (notify.getBooleanExtra(Canstants.NOTIFY_KEY_FROM, false)) {
            if (notify.getBooleanExtra(Canstants.NOTIFY_KEY_IS_CHAT, false)) {
                int chatType = notify.getIntExtra(Canstants.NOTIFY_KEY_TYPE, -1);
                if (chatType != -1) {
                    int id = notify.getIntExtra(Canstants.NOTIFY_KEY_TARGET_ID, -1);
                    if (id != -1) {
                        String name = notify.getStringExtra(Canstants.NOTIFY_KEY_TARGET_NAME);
                        String type = notify.getStringExtra(Canstants.NOTIFY_KEY_TARGET_TYPE);
                        GroupChatActivity.jumpTo(this, chatType, name, String.valueOf(id), type);
                    }
                }
            } else {
                navView.postDelayed(() -> setTopTab(3, false), 300);
            }
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!isForeground) {
            //后台进前台
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        selectNum();
    }

    @Override
    protected void onStop() {
        dismissNet(isShowDefNetDialog());
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (navChatFragment != null) {
            navChatFragment.setInit(true);
        }
        NetStateChangeReceiver.unRegisterReceiver(this, this);
        ScreenStateChangeReceive.unRegisterReceiver(this);
//        ObserverThread.unregisterRefreshData(this);
        presenter.onDestroy();
        if (connectHandler != null) {
            connectHandler.removeCallbacksAndMessages(null);
            connectHandler = null;
        }

    }

    private void selectShow(Fragment fragment) {
//        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//        if (fragment.isAdded()) {
//            if (currtShowFragment == null || currtShowFragment == fragment) {
//                transaction.show(fragment).commitAllowingStateLoss();
//            } else {
//                transaction.show(fragment).hide(currtShowFragment).commitAllowingStateLoss();
//            }
//        } else {
//            if (currtShowFragment == null || currtShowFragment == fragment) {
//                transaction.add(R.id.frame_content, fragment).show(fragment).commitAllowingStateLoss();
//            } else {
//                transaction.add(R.id.frame_content, fragment).show(fragment).hide(currtShowFragment).commitAllowingStateLoss();
//            }
//
//        }
//        currtShowFragment = fragment;
//        navView.post(() -> setTopTab(fragment));


    }

    private void setTopTab(Fragment fragment) {
        if (fragment != null && fragment.isAdded()) {
            mainMenuPop.getPopupWindow().dismiss();
            GlideUtil.getInstance().clear(getToolbarRightIv());
            if (fragment instanceof NavChatFragment) {
                getToolbar().setTitle("无痕通讯");
                //                R.mipmap.tab_btn_add
                showTitleRightTab();
            } else if (fragment instanceof NavContactFragment) {
                getToolbar().setTitle("好友");
//                R.mipmap.ic_search_friend
                showTitleRightTab();
            } else if (fragment instanceof NavGroupFragment) {
                getToolbar().setTitle("群组");
//                R.mipmap.ic_search_group
                showTitleRightTab();
            } else if (fragment instanceof NavNotifyFragment) {
                getToolbar().setTitle("通知");
                getToolbarRightIv().setVisibility(View.GONE);
                getToolbarRightIv2().setVisibility(View.GONE);
            } else if (fragment instanceof NavMeFragment) {
                getToolbar().setTitle(null);
                getToolbarRightIv().setVisibility(View.GONE);
                getToolbarRightIv2().setVisibility(View.GONE);
            }

        }

    }

    private void setTopTab(int position) {
        setTopTab(position, true);
    }

    private void setTopTab(int position, boolean smoothScroll) {
        if (!manualDraging) {
            pagerView.setCurrentItem(position, smoothScroll);
        }

        mainMenuPop.getPopupWindow().dismiss();
        GlideUtil.getInstance().clear(getToolbarRightIv());
        if (position == 0) {
            setTheme(this, true, R.color.title_color, R.color.title_color);
            getToolbar().setTitle("无痕通讯");
            showTitleRightTab();
        } else if (position == 1) {
            setTheme(this, true, R.color.title_color, R.color.title_color);
            getToolbar().setTitle("好友");
            showTitleRightTab();
        } else if (position == 2) {
            setTheme(this, true, R.color.title_color, R.color.title_color);
            getToolbar().setTitle("群组");
            showTitleRightTab();
        } else if (position == 3) {
            setTheme(this, true, R.color.title_color, R.color.title_color);
            getToolbar().setTitle("通知");
            getToolbarRightIv().setVisibility(View.GONE);
            getToolbarRightIv2().setVisibility(View.GONE);
        } else if (position == 4) {
            setTheme(ChatMainActivity.this, true, R.color.white, R.color.white);
            getToolbar().setTitle(null);
            getToolbarRightIv().setVisibility(View.GONE);
            getToolbarRightIv2().setVisibility(View.GONE);
        }
    }

    private void switchNav(int position) {
        mainMenuPop.getPopupWindow().dismiss();
        GlideUtil.getInstance().clear(getToolbarRightIv());
        if (position == 0) {
            navView.setSelectedItemId(R.id.navigation_chat);
        } else if (position == 1) {
            navView.setSelectedItemId(R.id.navigation_contact);
        } else if (position == 2) {
            navView.setSelectedItemId(R.id.navigation_group);
        } else if (position == 3) {
            navView.setSelectedItemId(R.id.navigation_notify);
        } else if (position == 4) {
            navView.setSelectedItemId(R.id.navigation_me);
        }
    }

    private void showTitleRightTab() {
        getToolbarRightIv().setVisibility(View.VISIBLE);
        getToolbarRightIv2().setVisibility(View.VISIBLE);
        GlideUtil.getInstance().load(R.mipmap.dialog_btn_add, getToolbarRightIv());
        GlideUtil.getInstance().load(R.mipmap.tab_btn_search, getToolbarRightIv2());
    }


    @Override
    protected ChatMainView bindNettyMessageView() {
        return new ChatMainView(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Canstants.KEY_GROUP_INVITE_RESULT == requestCode && Canstants.KEY_GROUP_INVITE_RESULT == resultCode) {
            openActivity(GroupChatActivity.class);
        } else if (Canstants.KEY_APPLY_AGREE_RESULT == requestCode && Canstants.KEY_APPLY_AGREE_RESULT == resultCode) {
            navView.postDelayed(() -> setTopTab(0, false), 300);
        }
    }

    @Override
    public void onNetDisconnected() {
        tvNoWifi.setVisibility(View.VISIBLE);
    }

    @Override
    public void onNetConnected(NetworkType networkType) {
        tvNoWifi.setVisibility(View.GONE);
        sendOnlineRequest();
    }

    private void sendOnlineRequest() {
        if (connectHandler == null) {
            connectHandler = new ConnectHandler(presenter);
        }
        if (connectHandler.hasMessages(1)) {
            connectHandler.removeMessages(1);
        }
        connectHandler.sendEmptyMessageDelayed(1, 1000);
    }

    public void selectNum() {
        ObserverThread.create().onNextThread1(new ObserverThread.OnMulActionListener() {
            @Override
            public void onAction(Object... obj) {
                setNotifySum((Long) obj[0]);
                setChatSum((Long) obj[1]);
                AppBadgerManager.count(ChatMainActivity.this, (int) (notifySum + chatSum));
            }

            @Override
            public Object[] onThreadAction() {
                return new Object[]{getNotifyUnReadNum(), ChatContentTable.getUnReadChatSum(ChatContentTable.queryList())};
            }
        });
    }

    @Override
    protected void afterOnCreateRegisterEventBus() {
        initDataForFirst();
        selectNum();
        presenter = new ChatMainPresenter(this);
        presenter.setOnNotifyListener(new ChatMainPresenter.OnNotifyListener() {
            @Override
            public void onChatContent() {
                refreshFragmentData();
                selectNum();
            }
        });
        presenter.setLoginoutListener(() -> {
            TcpLengthHeartbeatBroadcastReceive.loginOut();
            obtainView().doLogout();
            taskDelayed(() -> IMSClientHelper.getInstance().close(), 500);
            onGlobalLoginOut();
        });
        presenter.setLengthConnectedListener(this);
        NetStateChangeReceiver.registerReceiver(this, this);
        ScreenStateChangeReceive.registerReceiver(this, this);
        if (!NetUtils.isConnected(this)) {
            tvNoWifi.setVisibility(View.VISIBLE);
        } else {
            tvNoWifi.setVisibility(View.GONE);
        }
        sendOnlineRequest();
    }

    public long getNotifyUnReadNum() {
        long count = DbController.getInstance().getRead().getSysNoticeTableDao().queryBuilder().count();
        long count1 = DbController.getInstance().getRead().getBusinessLeaveTableDao().queryBuilder().where(BusinessLeaveTableDao.Properties.IsRead.eq(0), BusinessLeaveTableDao.Properties.LoginUserId.eq(ChatApp.getInstance().getUserId())).count();
        return count + count1;
    }

    private void refreshFragmentData() {
        if (navNotifyFragment != null) {
            navNotifyFragment.queryOfflineData();
        }
        selectNum();
//        if (navChatFragment != null) {
//            navChatFragment.queryOfflineData();
//        }
//        if (navContactFragment != null) {
//            navContactFragment.queryOfflineData();
//        }
//        if (navGroupFragment != null) {
//            navGroupFragment.queryOfflineData();
//        }
    }

    @Override
    public void onFriendListCallback(int code, String msg, List<FriendDto> data) {
        if (code == IMSContacts.ResponseCode.SUCCESS) {
            ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<List<FriendTable>>() {
                @Override
                public void onAction(List<FriendTable> list) {
                    if (list == null || list.isEmpty()) {
                        return;
                    }
                    navView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (navContactFragment != null) {
                                navContactFragment.setData(list);
                            }
                        }
                    }, 300);

                }

                @Override
                public List<FriendTable> onThreadAction() {
                    if (data != null && !data.isEmpty()) {
                        List<FriendTable> list = new ArrayList<>();
                        for (FriendDto datum : data) {
                            if (ChatApp.getInstance().getUserId().equals(datum.getFriendUserId())) {
                                continue;
                            }
                            FriendTable friendTable = FriendTable.getRowByFriendUserIdNotNull(datum.getFriendUserId());
                            friendTable.setFriendNickname(datum.getFriendNickname());
                            friendTable.setFriendUserId(datum.getFriendUserId());
                            friendTable.setFriendAlias(datum.getFriendAlias());
                            friendTable.setFriendId(datum.getFriendId());
                            friendTable.setFriendAvatar(datum.getFriendAvatar());
                            friendTable.setUserType(datum.getUserType());
                            friendTable.setSnapchatTimeUnit(datum.getSnapchatTimeUnit());
                            friendTable.setSnapchatTimeLength(datum.getSnapchatTimeLength());
                            friendTable.setSnapchatStatus(datum.isSnapchatStatus());
                            friendTable.setOnlineStatus(datum.getOnlineStatus());
                            friendTable.setOfflineMessage(datum.isOfflineMessage());
                            FriendTable.insert(friendTable);
                            list.add(friendTable);
                        }
                        return list;
                    }
                    return null;
                }
            });
            InitializeKit.friendInitialized();
        } else {
//            if (code != IMSContacts.ResponseCode.EMPTY_RESULT)
//                JToast.showShort(this, "好友列表初始化失败！");
        }
    }

    @Override
    public void onGroupListCallback(int code, String msg, List<GroupDto> data) {
        if (code == IMSContacts.ResponseCode.SUCCESS) {
            ObserverThread.create().onNextThread1(new ObserverThread.OnMulActionListener() {
                @Override
                public void onAction(Object... obj) {
                    List<GroupSimpleBean> createGroupList = (List<GroupSimpleBean>) obj[0];
                    List<GroupSimpleBean> joinGroupList = (List<GroupSimpleBean>) obj[1];
                    navView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (navGroupFragment != null) {
                                navGroupFragment.setGroupData(createGroupList, joinGroupList);
//                                navGroupFragment.refreshCreateGroup(createGroupList);
//                                navGroupFragment.refreshApplyedGroup(joinGroupList);
                            }
                        }
                    }, 300);
                }

                @Override
                public Object[] onThreadAction() {
                    List<GroupSimpleBean> createGroupList = new ArrayList<>();
                    List<GroupSimpleBean> joinGroupList = new ArrayList<>();
                    if (data != null && !data.isEmpty()) {
                        List<GroupTable> groupTables = new ArrayList<>();
                        for (GroupDto datum : data) {
                            GroupTable table = GroupTable.queryRowByGroupIdNotNull(datum.getGroupId());
                            table.setGroupOwnerId(datum.getGroupOwnerUserId());
                            table.setGroupId(datum.getGroupId());
                            table.setGroupName(datum.getGroupName());
                            table.setGroupAvatar(datum.getGroupAvatar());
                            table.setSnapchatTimeUnit(datum.getSnapchatTimeUnit());
                            table.setSnapchatTimeLength(datum.getSnapchatTimeLength());
                            table.setSnapchatStatus(datum.isSnapchatStatus());
                            table.setGroupType(IMSUtils.userTypeAnalysis(datum.getGroupId()));
                            table.setAnnouncementTitle(datum.getAnnouncementTitle());
                            table.setAnnouncementId(datum.getAnnouncementId());
                            table.setAnnouncementContent(datum.getAnnouncementContent());
                            table.setMemberCount(datum.getMemberCount());
                            GroupTable.insert(table);
                            groupTables.add(table);
                            //需修改
                            GroupSimpleBean g = new GroupSimpleBean();
                            g.setGroupId(datum.getGroupId());
                            g.setGroupName(datum.getGroupName());
                            g.setGroupType(datum.getGroupType());
                            g.setMemberCount(datum.getMemberCount());
                            if (!TextUtils.isEmpty(table.getGroupAvatar())) {
                                g.setMemberUserIds(table.getGroupId());
                                g.setMemberAvatarUrls(table.getGroupAvatar());
                            } else {
                                String[] v = GroupMemberTable.getAvatarEntityLoc(datum.getGroupId());
                                if (v != null) {
                                    g.setMemberUserIds(v[0]);
                                    g.setMemberAvatarUrls(v[1]);
                                    g.setMemberAvatarPaths(v[2]);
                                }
                            }
                            if (ChatApp.getInstance().getUserId().equals(datum.getGroupOwnerUserId())) {
                                g.setGroupCreateType(GroupSimpleBean.GREATE);
                                createGroupList.add(g);
                            } else {
                                g.setGroupCreateType(GroupSimpleBean.APPLYED);
                                joinGroupList.add(g);
                            }
                        }
                    }
                    InitializeKit.groupInitialized();
                    return new Object[]{createGroupList, joinGroupList};
                }
            });


        } else {
//            if (code != IMSContacts.ResponseCode.EMPTY_RESULT)
//                JToast.showShort(this, "群组列表初始化失败！");
        }

        mRequestOfflineMessageDelayMillis = 500;
        dismissNet(isShowDefNetDialog());
    }

    @Override
    public void onGetNotifyCallback(int code, String msg, List<SysNotifyDto> data) {
        if (!CollectionUtils.isEmpty(data)) {

        }
    }

    @Override
    public void onGetFriendOffMsgListCallback(int code, String msg, int page, boolean request) {
        if (obtainView().hasFriendOfflineTimeoutDelayed())
            removeTask(obtainView().getFriendOfflineTimeoutDelayed());
        if (code == IMSContacts.ResponseCode.TIMEOUT) {
            taskDelayed(obtainView().getFriendOfflineTimeoutDelayed(page), 5000);
        } else if (code == IMSContacts.ResponseCode.SUCCESS) {
            if (request)
                obtainView().doGetFriendOfflineMsgList(++page);
        }
    }

    @Override
    public void onGetGroupOffMsgListCallback(int code, String msg, int page, boolean request) {
        if (obtainView().hasGroupOfflineTimeoutDelayed())
            removeTask(obtainView().getGroupOfflineTimeoutDelayed());
        if (code == IMSContacts.ResponseCode.TIMEOUT) {
            taskDelayed(obtainView().getGroupOfflineTimeoutDelayed(page), 5000);
        } else if (code == IMSContacts.ResponseCode.SUCCESS) {
            if (request)
                obtainView().doGetGroupOfflineMsgList(++page);
        }
    }

    @Override
    public void onLogoutCallback(int code, String msg) {
        if (code == IMSContacts.ResponseCode.SUCCESS) {
//            if (navMeFragment != null)
//                navMeFragment.doQuit();
        } else {
//            JToast.showShort(this, msg);
        }
    }

    @Override
    public void onCheckVersionCallback(int code, String msg, VersionDto data) {
        if (code == IMSContacts.ResponseCode.SUCCESS && data != null && BuildConfig.VERSION_CODE < data.getVersionCode()) {
            final String serverPath = data.getUpdatePath();
            final String targetPath = VersionInfoActivity.getTargetPath(serverPath);
            final UpdateDialog mUpdateDialog = new UpdateDialog(this);
            mUpdateDialog.setContent(data.getUpdateDescribe());
            final FileTransmissionManager.Downloader downloader = FileTransmissionManager.getInstance().buildDownloader()
                    .targetPath(targetPath)
                    .serverPath(serverPath)
                    .friend(OriginalPictureVideoTransmissionCreator.apk(UserPreferences.getUserId()))
                    .onFileReceiver(new FileTransmissionListener.OnFileReceiverListener() {
                        @Override
                        public void onStart() {
                            JToast.showShort(ChatMainActivity.this, "开始下载");
                            mUpdateDialog.setProgressText("开始下载");
                        }

                        @Override
                        public void onProgress(int progress) {
                            mUpdateDialog.setProgress(progress);
                            mUpdateDialog.setProgressText(progress + "%");
                        }

                        @Override
                        public void onComplete(String path) {
                            VersionInfoActivity.installApk(ChatMainActivity.this, path);
                            mUpdateDialog.setProgressText("点击安装");
                            mUpdateDialog.setProgressComplateClick(v -> VersionInfoActivity.installApk(ChatMainActivity.this, path));
                        }

                        @Override
                        public void onError(int code, String msg) {
                            mUpdateDialog.setProgressError("下载失败");
                        }
                    });

            if (data.getIsConstraint() == 1) {
                mUpdateDialog.setSubmit("立即下载", v -> downloader.download());
            } else {
                mUpdateDialog.setLeftSubmit("下次再说", null);
                mUpdateDialog.setRightSubmit("立即下载", v -> downloader.download());
            }
            mUpdateDialog.show();
        }
    }

    @Override
    public void onLoginCallback(int code, String msg, UserDto data) {
        if (IMSContacts.ResponseCode.SUCCESS == code && data != null) {
            obtainView().doGetOffMsgList();
        }
    }

    @Override
    public void onSettingsInfoCallback(int code, String msg, SettingsDto data) {
        if (code == IMSContacts.ResponseCode.SUCCESS && data != null) {
            SharedUserUtils.put(mContext, Canstants.getClearKey(), data.isExitClean());
            int timerClean = data.getTimerClean() - 1;
            if (timerClean >= 0 && timerClean <= 2) {
                SharedUserUtils.put(mContext, Canstants.getSysClearCycKey(), timerClean);
                SharedUserUtils.put(mContext, Canstants.getSysClearCycTimeKey(), Calendar.getInstance().get(Calendar.DAY_OF_YEAR));
            }
        }
    }


    private void initDataForFirst() {
        obtainView().doCheckUpdate();
        obtainView().doGetSettingsInfo();
        boolean friend = InitializeKit.isFriendInitialize();
        boolean group = InitializeKit.isGroupInitialize();
        if (isInitializeData && (friend || group)) {
            showNet("初始化数据", false);
            taskDelayed(() -> {
                if (friend)
                    obtainView().doGetFriendList();
                if (group)
                    obtainView().doGetGroupList();
            }, 500);
            mRequestOfflineMessageDelayMillis = 2000;
        } else {
            mRequestOfflineMessageDelayMillis = 500;
        }
    }

    @Override
    public void onScreen(boolean isScreenOn) {
        presenter.onScreen(isScreenOn);
        if (isScreenOn) {
            sendOnlineRequest();
        }
    }

    private long mConnectedTime;

    @Override
    public void onConnected() {
        long currentConnectedTime = System.currentTimeMillis();
        if (mConnectedTime == 0 || currentConnectedTime - mConnectedTime > 1000) {
            taskDelayed(() -> obtainView().doLogin(), mRequestOfflineMessageDelayMillis);
            mConnectedTime = currentConnectedTime;
        }
//        if (isScreenOn) {
//        taskDelayed(() -> obtainView().doGetOffMsgList(), mRequestOfflineMessageDelayMillis);
//        }
    }

    static void jumpTo(Context context, boolean isInitialize) {
        Intent intent = new Intent(context, ChatMainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("is_initialize_data", isInitialize);
        context.startActivity(intent);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUiRefreshNotification(MessageEvent me) {
        if (me == null || me.event() != EventConstants.Event.UI_REFRESH_NOTIFICATION) return;
        if (me.action() == EventConstants.Action.ON_DELETE_HISTORY ||
                me.action() == EventConstants.Action.MESSAGE_CLEAR) { // 收到定期清理消息需要刷新
            // 退出清理后清空列表
//            if (navChatFragment != null)
            navChatFragment.queryOfflineData();
            selectNum();
        } else if (me.action() == EventConstants.Action.DELETE_FRIEND) {
            refreshFragment();
        } else if (me.action() == EventConstants.Action.GROUP_REFRESH ||
                me.action() == EventConstants.Action.DELETE_GROUP ||
                me.action() == EventConstants.Action.DISSOLVE_GROUP ||
                me.action() == EventConstants.Action.EXIT_GROUP) {
            refreshF();
        } else if (me.action() == EventConstants.Action.NOTIFY_NUMBER_CHANGED) {
            selectNum();
        } else if (me.action() == EventConstants.Action.CHAT_REFRESH || me.action() == EventConstants.Action.CHAT_REFRESH_AND_FRIEND) {
            if (me.action() == EventConstants.Action.CHAT_REFRESH_AND_FRIEND) {
//                                    if (navContactFragment != null)
                navContactFragment.queryOfflineData();
            }
            if (!TextUtils.isEmpty(me.data())) {
                try {
                    UserChatTable uChatTable = new Gson().fromJson(me.data(), UserChatTable.class);
                    ObserverThread.create().onNextThread0(new ObserverThread.OnActionListener<Object>() {
                        @Override
                        public void onAction(Object obj) {
                            navView.postDelayed(() -> {
//                                if (navChatFragment != null) {
                                navChatFragment.update((ChatContentTable) obj);
//                                }
                                selectNum();
                            }, 300);

                        }

                        @Override
                        public Object onThreadAction() {
                            return ChatContentTable.updateLastMsgById(uChatTable.getTargetId(), uChatTable.getTargetName(), uChatTable.isStartReadFinish(), uChatTable.getMsgType(), uChatTable.getText(), uChatTable.getTime(), uChatTable.getChatType(), uChatTable.isTaskDestory(), uChatTable.getReceiveType(), uChatTable.getTargetAlias());
                        }
                    });
                } catch (JsonSyntaxException e) {
                    Logger.print(e.getLocalizedMessage());
                }
            }
        }
    }

    private void refreshF() {
        navView.postDelayed(() -> {
//            if (navChatFragment != null)
            navChatFragment.queryOfflineData();
//            if (navGroupFragment != null)
            navGroupFragment.queryOfflineData();
            selectNum();
        }, 200);
    }

    private void refreshFragment() {
        navView.postDelayed(() -> {
//            if (navChatFragment != null)
            navChatFragment.queryOfflineData();
//            if (navContactFragment != null)
            navContactFragment.queryOfflineData();
            selectNum();
        }, 200);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) { // 将返回键改成HOME键
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }


    public static class ConnectHandler extends Handler {
        private ChatMainPresenter presenter;

        public ConnectHandler(ChatMainPresenter presenter) {
            this.presenter = presenter;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1 && presenter != null) {
                presenter.connect();
            }
        }
    }
}
